package ctm.javacode;

import javax.naming.*;
import javax.sql.DataSource;
import java.io.Serializable;
import java.sql.*;
import java.io.*;

public class dbBean implements Serializable {

	/** 
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Connection conn ;
	private DataSource dataSource;
	private Statement state ;

	
	public dbBean() {		
	} // end DbBean()	
	
	public dbBean( String dS ) throws NamingException {
		try {
			Context initContext = new InitialContext() ;
		    Context envContext = (Context)
							initContext.lookup("java:/comp/env");
		    dataSource = (DataSource) envContext.lookup(dS);
		} catch (NamingException ex) {
			throw new RuntimeException(ex);
		} // end catch
		
	} // end DbBean()
	
	
	public void Connected() {
		
		boolean ok = false ;
		SQLException ex = null ;
		conn = null ;
		
		try {
			conn = dataSource.getConnection();
			state = conn.createStatement() ;
		} catch (SQLException e) {
			ex = e ;
		} finally {
			
			if (ex != null) {
				throw new RuntimeException(ex) ;
			} // end if
		} // end try-catch-finally
	} // end isConnectedOK
	
	public ResultSet ExcuteQuery ( String sqlStatement ) throws SQLException {
		
		return state.executeQuery(sqlStatement) ;
		
	} // end ExcuteQuery()	
	
	public void ExcuteUpdate ( String sqlStatement ) throws SQLException {
		
		state.executeUpdate(sqlStatement) ;
		
	} // end ExcuteUpdate()	
	
	public void setDataSource ( String dS ) {
		try {
			Context initContext = new InitialContext() ;
		    Context envContext = (Context)
							initContext.lookup("java:/comp/env");
		    dataSource = (DataSource) envContext.lookup(dS);
		} catch (NamingException ex) {
			throw new RuntimeException(ex);
		} // end catch
	} // end setDataSource()
	
	public void CloseConn() throws SQLException {
		conn.close() ;
		state.close();		
	} // end CloseConn()
	
} // end class DbBean

